import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/foundation.dart';
import 'package:weightsmartlightapp/device_name.dart';
import 'blueUuid.dart';

class ConnectPage extends StatefulWidget {//因为要在widget构建完之后去执行业务逻辑，所以只能用StatefulWidget，因为这样才有initState方法
  final String deviceName;//用于传给底层的设备名称
  const ConnectPage({Key key, @required this.deviceName}) :super(key:key);//调用父类的构造函数的话如果写在大括号里面的话会报错,添加const关键字的话如果有方法体也会报错

  @override
  State<StatefulWidget> createState() =>_ConnectPageState();
}

class _ConnectPageState extends State<ConnectPage> {
  String _connectStateText='正在连接......';
  static const platform = const MethodChannel('my.flutter.io/bluetooth');//定义与底层操作系统的方法调用通道
  static const EventChannel _eventChannelPlugin = EventChannel('my.flutter.event/bluetooth');//定义接收底层操作系统主动发来的消息通道
  StreamSubscription _streamSubscription;//广播流来处理EventChannel发来的消息


  //widget初始化之后调用
  void afterBuildCallback(BuildContext context){
    print('进入了afterBuildCallback');
    _callPlatformConnectDevice(widget.deviceName);//调用底层去连接蓝牙设备
  }

  void changeText(String text){
    setState(() {
      _connectStateText=text;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('连接页面'),
      ),
      body: Center(
        child:  Text(_connectStateText),
      ),
    );
  }

  @override
  void initState() {//当Widget第一次插入到Widget树时会被调用,并且只会调用一次
    super.initState();
    _streamSubscription=_eventChannelPlugin
        .receiveBroadcastStream()
        .listen(_onToDart, onError: _onToDartError);//注册消息回调函数
    WidgetsBinding.instance.addPostFrameCallback((_) => afterBuildCallback(context));//注册一个回调函数在widget初始化完成之后调用
  }

  @override
  void dispose() {//当State对象从树中被永久移除时调用
    if (_streamSubscription != null) {
      _streamSubscription.cancel();//取消对底层的消息接收
      _streamSubscription = null;
    }
    super.dispose();
  }

  void _onToDart(dynamic message) {//底层发送成功消息时会进入到这个函数来接收
    switch(message['code']){
      case "80001"://如果是连接成功
          if(message['deviceName']==DeviceName.LIGHT_DEVICE_NAME)//如果是冷暖灯连接成功
            Navigator.pushNamed(context, "smart_light_controller");
          else if(message['deviceName']==DeviceName.WEIGHT_DEVICE_NAME)//如果是体重秤连接成功
            Navigator.pushNamed(context, "weight_controller");
          break;
      case "80002"://如果连接被手动断开
        print('connect.dart收到连接被手动断开的消息');
        Navigator.popUntil(context, ModalRoute.withName('home'));//就直接回到主界面
        break;
    }
  }
  void _onToDartError(dynamic error) {//底层发送错误消息时会进入到这个函数来接收
    switch(error.code){
      case "90001"://如果扫描不到目标设备
        print('connect.dart收到扫描不到设备的消息');
        Navigator.popUntil(context, ModalRoute.withName('home'));//就直接回到主界面
        break;
      case "90002"://与设备的连接断开
        print('connect.dart收到扫与设备的连接断开的消息');
        _callPlatformConnectDevice(error.details);//调用底层去连接蓝牙设备
        break;
    }
  }

  //调用底层去连接蓝牙设备
  void _callPlatformConnectDevice(String deviceName){
    Map<String,Object> dataMap;
    switch(deviceName){
      case DeviceName.LIGHT_DEVICE_NAME://如果是冷暖灯
        dataMap={
          "deviceName":deviceName,
          "uuidDataType":defaultTargetPlatform==TargetPlatform.android?BlueUuid.androidLightUuidType:null,
          "deviceUuid":defaultTargetPlatform==TargetPlatform.android?BlueUuid.androidLightUuid:BlueUuid.iosLightUuid,
          "notify_d":defaultTargetPlatform==TargetPlatform.android?BlueUuid.androidNotify_d:null,
          "notifyUuid":defaultTargetPlatform==TargetPlatform.android?BlueUuid.androidLightNotifyUuid:BlueUuid.iosLightNotifyUuid
        };
        break;
      case DeviceName.WEIGHT_DEVICE_NAME://如果是体重秤
        dataMap={
          "deviceName":deviceName,
          "uuidDataType":defaultTargetPlatform==TargetPlatform.android?BlueUuid.androidWeightUuidType:null,
          "deviceUuid":defaultTargetPlatform==TargetPlatform.android?BlueUuid.androidWeightUuid:BlueUuid.iosWeightUuid,
          "notify_d":defaultTargetPlatform==TargetPlatform.android?BlueUuid.androidNotify_d:null,
          "notifyUuid":defaultTargetPlatform==TargetPlatform.android?BlueUuid.androidWeightNotifyUuid:BlueUuid.iosWeightNotifyUuid
        };
        break;
    }
    platform.invokeMethod('connectDevice',dataMap).then((value){print(value);});//调用底层去连接蓝牙设备
  }
}